<template>
  <div class="export-page">
    <!-- 导出按钮区域（按数据类型分组） -->
    <div class="export-group">
      <h3>居民既往史导出</h3>
      <div class="export-buttons">
        <el-button type="primary" @click="handleExport('xlsx', 'medical')">导出 Excel</el-button>
        <el-button type="primary" @click="handleExport('csv', 'medical')">导出 CSV</el-button>
        <el-button type="primary" @click="handleExport('pdf', 'medical')">导出 PDF</el-button>
        <el-button type="primary" @click="handleExportDom('medical')">导出表格 DOM 为 PDF</el-button>
      </div>
    </div>

    <div class="export-group">
      <h3>家庭创建信息导出</h3>
      <div class="export-buttons">
        <el-button type="primary" @click="handleExport('xlsx', 'familyCreate')">导出 Excel</el-button>
        <el-button type="primary" @click="handleExport('csv', 'familyCreate')">导出 CSV</el-button>
        <el-button type="primary" @click="handleExport('pdf', 'familyCreate')">导出 PDF</el-button>
        <el-button type="primary" @click="handleExportDom('familyCreate')">导出表格 DOM 为 PDF</el-button>
      </div>
    </div>

    <div class="export-group">
      <h3>家庭加入信息导出</h3>
      <div class="export-buttons">
        <el-button type="primary" @click="handleExport('xlsx', 'familyJoin')">导出 Excel</el-button>
        <el-button type="primary" @click="handleExport('csv', 'familyJoin')">导出 CSV</el-button>
        <el-button type="primary" @click="handleExport('pdf', 'familyJoin')">导出 PDF</el-button>
        <el-button type="primary" @click="handleExportDom('familyJoin')">导出表格 DOM 为 PDF</el-button>
      </div>
    </div>

    <!-- 数据表格（按类型分别展示，用于DOM导出） -->
    <el-table 
      id="medicalTable" 
      :data="state.medicalHistoryTableData" 
      border 
      style="width: 100%; margin-top: 10px;"
    >
      <el-table-column prop="historyType" label="既往史分类" :formatter="formatHistoryType" width="150" />
      <el-table-column prop="historyName" label="既往史名称" :formatter="formatHistoryName" width="150" />
      <el-table-column prop="occurDate" label="发生日期" :formatter="(row: MedicalHistoryItem) => ExportFormatters.date(row.occurDate)" width="150" />
      <el-table-column prop="institutionName" label="机构名称" width="200" />
      <el-table-column prop="description" label="描述" />
      <el-table-column prop="startDate" label="开始日期" :formatter="(row: MedicalHistoryItem) => ExportFormatters.date(row.startDate)" width="150" />
      <el-table-column prop="endDate" label="结束日期" :formatter="(row: MedicalHistoryItem) => ExportFormatters.date(row.endDate)" width="150" />
    </el-table>

    <el-table 
      id="familyCreateTable" 
      :data="state.familyCreateTableData" 
      border 
      style="width: 100%; margin-top: 20px;"
    >
      <el-table-column prop="relationship" label="关系" :formatter="formatRelationship" width="120" />
      <el-table-column prop="name" label="姓名" width="120" />
      <el-table-column prop="idType" label="证件类型" :formatter="formatIdType" width="150" />
      <el-table-column prop="idNumber" label="证件号码" width="200" />
      <el-table-column prop="phone" label="联系电话" width="150" />
      <el-table-column prop="isHouseholdHead" label="是否户主" :formatter="(row: FamilyCreateItem) => ExportFormatters.boolean(row.isHouseholdHead)" width="120" />
    </el-table>

    <el-table 
      id="familyJoinTable" 
      :data="state.familyJoinTableData" 
      border 
      style="width: 100%; margin-top: 20px;"
    >
      <el-table-column prop="relationship" label="与户主关系" :formatter="formatRelationship" width="150" />
      <el-table-column prop="familyCode" label="家庭编号" width="180" />
      <el-table-column prop="name" label="姓名" width="120" />
      <el-table-column prop="idNumber" label="证件号码" width="200" />
      <el-table-column prop="phone" label="联系电话" width="150" />
    </el-table>
  </div>
</template>

<script setup lang="ts">
import { reactive } from "vue";
import { exportFile, ExportFormatters, ExportColumn } from '@/utils/exportFile';

// 1. 定义所有数据类型的接口
interface MedicalHistoryItem {
  id: number;
  historyType: 'DISEASE' | 'SURGERY' | 'ALLERGY' | 'OTHER' | '';
  historyName: 'HYPERTENSION' | 'DIABETES' | 'CORONARY' | 'OTHER' | '';
  description: string;
  institutionName: string;
  occurDate: string | Date | '';
  startDate: string | Date | '';
  endDate: string | Date | '';
}

interface FamilyCreateItem {
  id: number;
  relationship: 'SELF' | 'WIFE' | 'SON' | 'DAUGHTER' | '';
  name: string;
  idType: 'VISION' | 'HEARING' | 'LIMB' | 'OTHER' | '';
  idNumber: string;
  phone: string;
  isHouseholdHead: boolean;
}

interface FamilyJoinItem {
  id: number;
  relationship: 'SELF' | 'WIFE' | 'SON' | 'DAUGHTER' | '';
  familyCode: string;
  name: string;
  idNumber: string;
  phone: string;
}

// 2. 状态管理（包含所有数据集）
const state = reactive({
  // 居民既往史数据
  medicalHistoryTableData: [
    {
      id: Date.now(),
      historyType: 'DISEASE',
      historyName: 'HYPERTENSION',
      description: '原发性高血压，病史5年，规律服药',
      institutionName: 'XX社区卫生服务中心',
      occurDate: '2019-03-15',
      startDate: '2019-03-20',
      endDate: ''
    },
    {
      id: Date.now() + 1,
      historyType: 'SURGERY',
      historyName: 'OTHER',
      description: '阑尾切除术，术后恢复良好',
      institutionName: 'XX市第一医院',
      occurDate: '2017-08-09',
      startDate: '2017-08-09',
      endDate: '2017-08-20'
    }
  ] as MedicalHistoryItem[],

  // 家庭创建信息数据
  familyCreateTableData: [
    {
      id: Date.now(),
      relationship: 'SELF',
      name: '张三',
      idType: 'OTHER',
      idNumber: '430102199001011234',
      phone: '13800138000',
      isHouseholdHead: true
    },
    {
      id: Date.now() + 1,
      relationship: 'WIFE',
      name: '李四',
      idType: '',
      idNumber: '430102199202021234',
      phone: '13900139000',
      isHouseholdHead: false
    }
  ] as FamilyCreateItem[],

  // 家庭加入信息数据
  familyJoinTableData: [
    {
      id: Date.now(),
      relationship: 'SON',
      familyCode: 'FAM_20240520_001',
      name: '张小明',
      idNumber: '430102201505051234',
      phone: '13700137000'
    },
    {
      id: Date.now() + 1,
      relationship: 'DAUGHTER',
      familyCode: 'FAM_20240520_001',
      name: '张小红',
      idNumber: '430102201808081234',
      phone: '13600136000'
    }
  ] as FamilyJoinItem[],
});

// 3. 通用格式化函数（多数据集复用）
const formatRelationship = (row: FamilyCreateItem | FamilyJoinItem) => {
  const map = { SELF: '本人', WIFE: '老婆', SON: '儿子', DAUGHTER: '女儿' };
  return (map as Record<string, string>)[row.relationship] || '未填写';
};

const formatIdType = (row: FamilyCreateItem) => {
  const map = { VISION: '视力残疾', HEARING: '听力残疾', LIMB: '肢体残疾', OTHER: '其他' };
  return (map as Record<string, string>)[row.idType] || '未填写';
};

const formatHistoryType = (row: MedicalHistoryItem) => {
  const map = { DISEASE: '疾病史', SURGERY: '手术史', ALLERGY: '过敏史', OTHER: '其他' };
  return (map as Record<string, string>)[row.historyType] || '未填写';
};

const formatHistoryName = (row: MedicalHistoryItem) => {
  const map = { HYPERTENSION: '高血压', DIABETES: '糖尿病', CORONARY: '冠心病', OTHER: '其他' };
  return (map as Record<string, string>)[row.historyName] || '未填写';
};

// 4. 各数据集的导出配置（列映射）
// 4.1 既往史导出配置
const medicalExportColumns: ExportColumn<MedicalHistoryItem>[] = [
  { key: 'historyType', title: '既往史分类', formatter: formatHistoryType },
  { key: 'historyName', title: '既往史名称', formatter: formatHistoryName },
  { key: 'occurDate', title: '发生日期', formatter: (v) => ExportFormatters.date(v) },
  { key: 'startDate', title: '开始日期', formatter: (v) => ExportFormatters.date(v) },
  { key: 'endDate', title: '结束日期', formatter: (v) => ExportFormatters.date(v) },
  { key: 'institutionName', title: '机构名称' },
  { key: 'description', title: '描述' },
];

// 4.2 家庭创建信息导出配置
const familyCreateExportColumns: ExportColumn<FamilyCreateItem>[] = [
  { key: 'relationship', title: '关系', formatter: formatRelationship },
  { key: 'name', title: '姓名' },
  { key: 'idType', title: '证件类型', formatter: formatIdType },
  { key: 'idNumber', title: '证件号码' },
  { key: 'phone', title: '联系电话' },
  { key: 'isHouseholdHead', title: '是否户主', formatter: (v) => ExportFormatters.boolean(v) },
];

// 4.3 家庭加入信息导出配置
const familyJoinExportColumns: ExportColumn<FamilyJoinItem>[] = [
  { key: 'relationship', title: '与户主关系', formatter: formatRelationship },
  { key: 'familyCode', title: '家庭编号' },
  { key: 'name', title: '姓名' },
  { key: 'idNumber', title: '证件号码' },
  { key: 'phone', title: '联系电话' },
];

// 5. 统一导出处理函数（按数据集类型区分）
const handleExport = (format: 'xlsx' | 'csv' | 'pdf', dataType: 'medical' | 'familyCreate' | 'familyJoin') => {
  // 配置映射表，避免冗长的 if-else 判断
  const configMap = {
    medical: {
      data: state.medicalHistoryTableData,
      fileName: `居民既往史_${new Date().getTime()}`,
      columns: medicalExportColumns,
      sheetName: '居民既往史'
    },
    familyCreate: {
      data: state.familyCreateTableData,
      fileName: `家庭创建信息_${new Date().getTime()}`,
      columns: familyCreateExportColumns,
      sheetName: '家庭创建信息'
    },
    familyJoin: {
      data: state.familyJoinTableData,
      fileName: `家庭加入信息_${new Date().getTime()}`,
      columns: familyJoinExportColumns,
      sheetName: '家庭加入信息'
    }
  };

  const config = configMap[dataType];
  exportFile({ ...config, format });
};

// 6. DOM导出PDF（按数据集类型区分）
const handleExportDom = (dataType: 'medical' | 'familyCreate' | 'familyJoin') => {
  const domMap = {
    medical: 'medicalTable',
    familyCreate: 'familyCreateTable',
    familyJoin: 'familyJoinTable'
  };
  const domId = domMap[dataType];

  exportFile({
    data: [],
    fileName: `${dataType === 'medical' ? '居民既往史' : dataType === 'familyCreate' ? '家庭创建信息' : '家庭加入信息'}_表格导出_${new Date().getTime()}`,
    format: 'pdf',
    columns: [],
    domSelector: `#${domId}`,
  });
};
</script>

<style scoped>
.export-page {
  padding: 20px;
}

.export-group {
  margin-bottom: 30px;
  padding: 15px;
  border: 1px solid #f0f0f0;
  border-radius: 4px;
}

.export-group h3 {
  margin: 0 0 15px 0;
  font-size: 16px;
  color: #333;
}

.export-buttons {
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
}
</style>